"""
用户分群相关接口
"""
from fastapi import APIRouter
from schemas import schema_tag
from models import model_tag, model_group, user_profile
from utils.explain import *

router_tag = APIRouter(prefix='/data_tag', tags=['标签管理'])


@router_tag.get('/', summary='查询所有属性')
async def get_tag_list(page: int, limit: int):
    """分页查询列表"""
    item = await model_tag.DataTag.filter().offset(page * limit).limit(limit)
    return item


@router_tag.post('/', summary='新增属性')
async def add_tag_detail(item: schema_tag.AddTag):
    item = await model_tag.DataTag.create(tag_name=item.tag_name,
                                          tag_desc=item.tag_desc,
                                          tag_type=item.tag_type,
                                          tag_data_type=item.tag_data_type,
                                          tag_data_dict=item.tag_data_dict)
    return item


@router_tag.get('/{tag_id}', summary='获取属性详细信息')
async def get_tag_detail(tag_id: int):
    item = await model_tag.DataTag.get(tag_id=tag_id)
    return item


@router_tag.put('/{tag_id}', summary='修改属性详细信息')
async def update_tag_detail(item: schema_tag.Tag):
    item = await model_tag.DataTag.filter(tag_id=item.tag_id).update(tag_name=item.tag_name,
                                                                     tag_desc=item.tag_desc,
                                                                     tag_type=item.tag_type,
                                                                     tag_data_type=item.tag_data_type,
                                                                     tag_data_dict=item.tag_data_dict)
    return item


@router_tag.delete('/{tag_id}', summary='删除属性详细信息')
async def delete_tag_detail(tag_id: int):
    item = await model_tag.DataTag.filter(tag_id=tag_id).delete()
    return item


@router_tag.post('/profile/{group_id}', summary='创建人群内容')
async def create_profile_list(group_id: int):
    filter_json = await model_group.Group.get(group_id=group_id)
    code = f"select id from user_profile where " + explain_json(filter_json.configs)
    result = await user_profile.UserProfile.raw(code)
    for res in result:
        await model_group.GroupLink.create(link_id=res.id, group_id=group_id)
    return len(result)


@router_tag.get('/profile/{group_id}', summary='获取人群内容')
async def get_profile_list(group_id: int):
    result = await model_group.GroupLink.filter(group_id=group_id).all().values('link_id')
    return [item['link_id'] for item in result]
